<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <div class="flex items-center space-x-4 mb-4">
          <div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl flex items-center justify-center">
            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
            </svg>
          </div>
          <div>
        <h1 class="text-3xl font-bold text-gray-900">我的收藏</h1>
        <p class="text-gray-600">收藏的题目和资源</p>
          </div>
        </div>
        
        <!-- 统计信息 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <StatsCard
            label="总收藏"
            :value="totalFavorites"
            icon="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
            color="blue"
          />
          <StatsCard
            label="题目收藏"
            :value="questionCount"
            icon="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
            color="green"
          />
          <StatsCard
            label="资源收藏"
            :value="resourceCount"
            icon="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"
            color="purple"
          />
          <StatsCard
            label="竞赛收藏"
            :value="contestCount"
            icon="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
            color="yellow"
          />
        </div>
      </div>

      <!-- 筛选器 -->
      <Card class="mb-6" variant="elevated">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">类型筛选</label>
            <select
              v-model="selectedType"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
              @change="handleFilter"
            >
              <option value="">所有类型</option>
              <option value="question">题目</option>
              <option value="resource">资源</option>
              <option value="contest">竞赛</option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">难度筛选</label>
            <select
              v-model="selectedDifficulty"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
              @change="handleFilter"
            >
              <option value="">所有难度</option>
              <option value="Easy">简单</option>
              <option value="Medium">中等</option>
              <option value="Hard">困难</option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">搜索</label>
            <div class="relative">
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索收藏..."
                class="w-full px-3 py-2 pl-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
              @input="handleSearch"
            />
              <svg class="absolute left-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
            </div>
          </div>

          <div class="flex items-end">
            <Button
              variant="outline"
              @click="clearFilters"
              class="w-full"
            >
              清除筛选
            </Button>
          </div>
        </div>
      </Card>

      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        <span class="ml-2 text-gray-600">加载中...</span>
      </div>

      <!-- 收藏列表 -->
      <div v-else-if="mergedFavorites.length > 0" class="space-y-4">
        <!-- 题目收藏 -->
        <div v-if="questionFavorites.length > 0">
          <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
            <svg class="w-5 h-5 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            题目收藏 ({{ questionFavorites.length }})
          </h3>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <QuestionCard
              v-for="(favorite, index) in questionFavorites"
              :key="favorite.id"
              :question="favorite.question!"
              :index="index"
              :current-page="currentPage"
              :page-size="pageSize"
              @favorite="handleFavorite"
              @unfavorite="handleUnfavorite"
            />
          </div>
        </div>

        <!-- 资源收藏 -->
        <div v-if="resourceFavorites.length > 0">
          <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
            <svg class="w-5 h-5 text-purple-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
            </svg>
            资源收藏 ({{ resourceFavorites.length }})
          </h3>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <ResourceCard
              v-for="favorite in resourceFavorites"
                :key="favorite.id"
              :resource="favorite.resource"
              @remove="handleRemoveFavorite"
            />
          </div>
                  </div>

        <!-- 竞赛收藏 -->
        <div v-if="contestFavorites.length > 0">
          <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center">
            <svg class="w-5 h-5 text-yellow-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
            </svg>
            竞赛收藏 ({{ contestFavorites.length }})
          </h3>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <ContestCard
              v-for="favorite in contestFavorites"
              :key="favorite.id"
              :contest="favorite.contest"
              @remove="handleRemoveFavorite"
            />
                  </div>
        </div>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="mt-8">
          <Card>
            <div class="flex items-center justify-between">
          <div class="flex-1 flex justify-between sm:hidden">
                <Button
              :disabled="currentPage === 1"
                  variant="outline"
              @click="goToPage(currentPage - 1)"
            >
              上一页
                </Button>
                <Button
              :disabled="currentPage === totalPages"
                  variant="outline"
              @click="goToPage(currentPage + 1)"
            >
              下一页
                </Button>
          </div>
          <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
            <div>
              <p class="text-sm text-gray-700">
                显示第
                <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span>
                到
                <span class="font-medium">{{ Math.min(currentPage * pageSize, totalFavorites) }}</span>
                条，共
                <span class="font-medium">{{ totalFavorites }}</span>
                条记录
              </p>
            </div>
            <div>
              <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                    <Button
                  :disabled="currentPage === 1"
                      variant="outline"
                      size="sm"
                  @click="goToPage(currentPage - 1)"
                >
                  上一页
                    </Button>
                    <Button
                  v-for="page in visiblePages"
                  :key="page"
                      :variant="page === currentPage ? 'primary' : 'outline'"
                      size="sm"
                  @click="goToPage(page)"
                >
                  {{ page }}
                    </Button>
                    <Button
                  :disabled="currentPage === totalPages"
                      variant="outline"
                      size="sm"
                  @click="goToPage(currentPage + 1)"
                >
                  下一页
                    </Button>
              </nav>
            </div>
          </div>
            </div>
          </Card>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!loading" class="text-center py-12">
        <div class="w-24 h-24 bg-gradient-to-r from-blue-100 to-purple-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <svg class="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
        </svg>
        </div>
        <h3 class="text-lg font-medium text-gray-900 mb-2">暂无收藏</h3>
        <p class="text-gray-500 mb-6">开始收藏你感兴趣的题目和资源吧</p>
        <Button
          variant="primary"
          @click="$router.push('/questions')"
        >
          去浏览题目
        </Button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { favoriteApi } from '@/api/favorite'
import { Card, Button, StatsCard } from '@/components'
import QuestionCard from '@/components/business/QuestionCard.vue'
import ResourceCard from '@/components/business/ResourceCard.vue'
import ContestCard from '@/components/business/ContestCard.vue'
import type { FavoriteItem } from '@/api/favorite'
import { useQuestionStore } from '@/stores/question'

const route = useRoute()
const router = useRouter()
const questionStore = useQuestionStore()

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const selectedType = ref('')
const selectedDifficulty = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const favorites = ref<FavoriteItem[]>([])
const totalFavorites = ref(0)

// 计算属性
const storeQuestionFavorites = computed<FavoriteItem[]>(() => {
  return (questionStore.favorites || []).map((q) => ({
    id: q.id,
    type: 'question',
    title: q.title,
    description: '',
    difficulty: q.difficulty as any,
    favorited_at: new Date().toISOString(),
    question: q
  }))
})
const mergedFavorites = computed<FavoriteItem[]>(() => {
  const apiQuestionItems = favorites.value.filter(f => f.type === 'question')
  const apiOtherItems = favorites.value.filter(f => f.type !== 'question')
  const storeIds = new Set(storeQuestionFavorites.value.map(f => f.question?.id || f.id))
  const dedupApiQuestions = apiQuestionItems.filter(f => !storeIds.has(f.question?.id || f.id))
  return [...storeQuestionFavorites.value, ...dedupApiQuestions, ...apiOtherItems]
})
const filteredFavorites = computed(() => {
  let filtered = mergedFavorites.value
  if (selectedType.value) {
    filtered = filtered.filter(f => f.type === selectedType.value)
  }
  if (selectedDifficulty.value) {
    filtered = filtered.filter(f => f.difficulty === selectedDifficulty.value)
  }
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(f =>
      f.title.toLowerCase().includes(query) ||
      (f.description && f.description.toLowerCase().includes(query))
    )
  }
  return filtered
})
const questionFavorites = computed(() => 
  filteredFavorites.value.filter(f => f.type === 'question')
)

const resourceFavorites = computed(() => 
  filteredFavorites.value.filter(f => f.type === 'resource')
)

const contestFavorites = computed(() => 
  filteredFavorites.value.filter(f => f.type === 'contest')
)

const questionCount = computed(() => 
  mergedFavorites.value.filter(f => f.type === 'question').length
)

const resourceCount = computed(() => 
  mergedFavorites.value.filter(f => f.type === 'resource').length
)

const contestCount = computed(() => 
  mergedFavorites.value.filter(f => f.type === 'contest').length
)

const totalPages = computed(() => Math.ceil(totalFavorites.value / pageSize.value))

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const loadFavorites = async () => {
  try {
    loading.value = true
    const response = await favoriteApi.getFavorites({
      type: selectedType.value as 'question' | 'resource' | 'contest' | undefined,
      difficulty: selectedDifficulty.value as 'Easy' | 'Medium' | 'Hard' | undefined,
      search: searchQuery.value || undefined,
      page: currentPage.value,
      page_size: pageSize.value
    })
    
    if (response.data) {
      favorites.value = response.data.items || []
      totalFavorites.value = response.data.total || 0
    } else {
      favorites.value = []
      totalFavorites.value = 0
    }
  } catch (error) {
    console.error('加载收藏数据失败:', error)
    favorites.value = []
    totalFavorites.value = 0
    // 可以添加错误提示
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadFavorites()
}

const handleFilter = () => {
  currentPage.value = 1
  loadFavorites()
}

const clearFilters = () => {
  selectedType.value = ''
  selectedDifficulty.value = ''
  searchQuery.value = ''
  currentPage.value = 1
  loadFavorites()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadFavorites()
  }
}

const handleFavorite = async (questionId: number) => {
  try {
    await questionStore.favoriteQuestion(questionId)
    // 后端数据对齐（获取服务器返回的favoriteId等）
    await loadFavorites()
  } catch (error) {
    console.error('收藏失败:', error)
  }
}

const handleUnfavorite = async (questionId: number) => {
  try {
    await questionStore.unfavoriteQuestion(questionId)
    // 后端数据对齐
    await loadFavorites()
  } catch (error) {
    console.error('取消收藏失败:', error)
  }
}

const handleRemoveFavorite = async (favoriteId: number) => {
  try {
    await favoriteApi.removeFavorite(favoriteId)
    await loadFavorites()
  } catch (error) {
    console.error('删除收藏失败:', error)
  }
}

// 监听路由变化
watch(() => route.params.id, () => {
  loadFavorites()
})

onMounted(() => {
  loadFavorites()
})
</script>

